﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using Microsoft.Win32;

namespace GenerateurMusique
{
    public partial class MainWindow : Window
    {

        MediaPlayer mplayer;
        Boolean isPlaying;
        string strFileName;
        int nbFile = 0;
        population pop;
        SaveFileDialog saveFileDialog1;

        public MainWindow()
        {
            InitializeComponent();

            // Initialisation du lecteur
            mplayer = new MediaPlayer();
            mplayer.MediaEnded += mplayer_MediaEnded;
            isPlaying = false;
            pop = new population(0.8, 0.3);
           
            for (int i = 0; i < pop.individus.Length; i++)
            {
               for(int j=0; j<pop.individus[i].notes.Length;j++){
                   Debug.Write(pop.individus[i].notes[j]+" ");
               }
               Debug.Write(pop.individus[i].instrument + " ");
               Debug.WriteLine(" ");
            }
            remplissagelabel(Label1, 0);
            remplissagelabel(Label2, 1);
            remplissagelabel(Label3, 2);
            remplissagelabel(Label4, 3);
            remplissagelabel(Label5, 4);
            remplissagelabel(Label6, 5);
            remplissagelabel(Label7, 6);
            remplissagelabel(Label8, 7);
            remplissagelabel(Label9, 8);
            remplissagelabel(Label10, 9);
            // On s'abonne à la fermeture du programme pour pouvoir nettoyer le répertoire et les fichiers midi
            this.Closed += MainWindow_Closed;
        }

        // On efface les fichiers .mid que l'on avait créé à la fin du programme
        void MainWindow_Closed(object sender, EventArgs e)
        {
            // s'il y a un fichier en cours de lecture on l'arrête 
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            var files = Directory.EnumerateFiles("./", "Fichier*.mid");
            foreach (string file in files)
            {
                File.Delete(file);
            }

        }

        // Lancé lorsque le fichier a fini sa lecture, pour le fermer proprement
        void mplayer_MediaEnded(object sender, EventArgs e)
        {
            mplayer.Stop();
            mplayer.Close();
            isPlaying = false;
        }

        // Clic sur le bouton : on lance la création d'un fichier et on le joue
        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            CreateAndPlayMusic();
        }

        private void PlayIndi(object sender, System.Windows.RoutedEventArgs e)
        {
            // ((Button)sender).Tag;
        }

        // Méthode principale
        private void CreateAndPlayMusic()
        {
            // s'il y a un fichier en cours de lecture on l'arrête
           
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            // Générateur aléatoire
            Random rand = new Random();

            // 1) Créer le fichier MIDI
            // a. Créer un fichier et une piste audio ainsi que les informations de tempo
            MIDISong song = new MIDISong();
            song.AddTrack("Piste1");
            song.SetTimeSignature(0, 4, 4);
            song.SetTempo(0, 150);

            // b. Choisir un instrument entre 1 et 128 
            // Liste complète ici : http://fr.wikipedia.org/wiki/General_MIDI
            int instrument = rand.Next(1, 129);
            Random rando = new Random(1); 
            Console.WriteLine("Instrument " + instrument + rando);
            
            song.SetChannelInstrument(0, 0, instrument);

            // c. Ajouter des notes
            // Chaque note est comprise entre 0 et 127 (12 correspond au type de note, fixe ici à des 1/4)
            // L'équivalence avec les notes / octaves est disponible ici : https://andymurkin.files.wordpress.com/2012/01/midi-int-midi-note-no-chart.jpg
            // Ici 16 notes aléatoire entre 16 et 96 (pour éviter certaines notes trop aigues ou trop graves)
            for (int i = 0; i < 16; i++)
            {
                int note = rand.Next(24, 96);
                song.AddNote(0, 0, note, 12);
            }

            // d. Enregistrer le fichier .mid (lisible dans un lecteur externe par exemple)
            // on prépare le flux de sortie
            MemoryStream ms = new MemoryStream();
            song.Save(ms);
            ms.Seek(0, SeekOrigin.Begin);
            byte[] src = ms.GetBuffer();
            byte[] dst = new byte[src.Length];
            for (int i = 0; i < src.Length; i++)
            {
                dst[i] = src[i];
            }
            ms.Close();
            // et on écrit le fichier
            strFileName = "Fichier" + nbFile + ".mid";
            FileStream objWriter = File.Create(strFileName);
            objWriter.Write(dst, 0, dst.Length);
            objWriter.Close();
            objWriter.Dispose();
            objWriter = null;

            // 2) Jouer un fichier MIDI
            mplayer.Open(new Uri(strFileName, UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier0.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier1.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier2.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier3.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier4.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier5.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier6.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier7.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_9(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier8.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Click_10(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
            mplayer.Open(new Uri("Fichier9.mid", UriKind.Relative));
            nbFile++;
            isPlaying = true;
            mplayer.Play();
        }

        private void Button_Save_1(object sender, RoutedEventArgs e)
        {

            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier0.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }

        private void Button_Save_2(object sender, RoutedEventArgs e)
        {
            if(!isPlaying){
                var fileStream = new FileStream(@"Fichier1.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }
        private void Button_Save_3(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier2.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }

        }
        private void Button_Save_4(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier3.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }
        private void Button_Save_5(object sender, RoutedEventArgs e)
        {
            if(!isPlaying){
                var fileStream = new FileStream(@"Fichier4.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }

        }
        private void Button_Save_6(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier5.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }
        private void Button_Save_7(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier6.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }



        private void Button_Save_8(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier7.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }

        private void Button_Save_9(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier8.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }

        private void Button_Save_10(object sender, RoutedEventArgs e)
        {
            if (!isPlaying)
            {
                var fileStream = new FileStream(@"Fichier9.mid", FileMode.Open);
                saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Midi Image|*.mid";
                saveFileDialog1.Title = "Save a new song";
                saveFileDialog1.ShowDialog();
                if (saveFileDialog1.FileName != "")
                {
                    var fileStreamDest = File.Create(saveFileDialog1.FileName);

                    fileStream.CopyTo(fileStreamDest);
                    fileStreamDest.Close();
                }
                fileStream.Close();
            }
            else
            {
                MessageBox.Show("Veuillez Attendre que la musique se finisse");
            }
        }


        private void Button_Click_11(object sender, RoutedEventArgs e)
        {
            if (isPlaying)
            {
                mplayer.Stop();
                mplayer.Close();
                isPlaying = false;
            }
                if (Note1.Text != "" && Note2.Text != "" && Note3.Text != "" && Note4.Text != "" && Note5.Text != "" && Note6.Text != "" && Note7.Text != "" && Note8.Text != "" && Note9.Text != "" && Note10.Text != "")
                {
                    int[] notes = new int[10];


                    notes[0] = int.Parse(Note1.Text);
                    notes[1] = int.Parse(Note2.Text);
                    notes[2] = int.Parse(Note3.Text);
                    notes[3] = int.Parse(Note4.Text);
                    notes[4] = int.Parse(Note5.Text);
                    notes[5] = int.Parse(Note6.Text);
                    notes[6] = int.Parse(Note7.Text);
                    notes[7] = int.Parse(Note8.Text);
                    notes[8] = int.Parse(Note9.Text);
                    notes[9] = int.Parse(Note10.Text);


                    pop.selection(notes);
                    
                    var files = Directory.EnumerateFiles("./", "Fichier*.mid");
                    foreach (string file in files)
                    {
                        File.Delete(file);
                    }
                    for (int i = 0; i < pop.individus.Length; i++)
                    {
                        pop.individus[i].CreateAndPlayMusic(i);
                        for (int j = 0; j < pop.individus[i].notes.Length; j++)
                        {
                            Debug.Write(pop.individus[i].notes[j]);

                        }
                        Debug.WriteLine(" ");
                    }

                    Note1.SelectedIndex = 5;
                    Note2.SelectedIndex = 5;
                    Note3.SelectedIndex = 5;
                    Note4.SelectedIndex = 5;
                    Note5.SelectedIndex = 5;
                    Note6.SelectedIndex = 5;
                    Note7.SelectedIndex = 5;
                    Note8.SelectedIndex = 5;
                    Note9.SelectedIndex = 5;
                    Note10.SelectedIndex = 5;

                    remplissagelabel(Label1, 0);
                    remplissagelabel(Label2, 1);
                    remplissagelabel(Label3, 2);
                    remplissagelabel(Label4, 3);
                    remplissagelabel(Label5, 4);
                    remplissagelabel(Label6, 5);
                    remplissagelabel(Label7, 6);
                    remplissagelabel(Label8, 7);
                    remplissagelabel(Label9, 8);
                    remplissagelabel(Label10, 9);

                }
            
            
        }
        void remplissagelabel(Label label,int i)
        {
            string temp = "";
            label.Content = "";
            for (int j = 0; j < pop.individus[i].notes.Length; j++)
            {
                temp += pop.individus[i].notes[j] + " ";
            }
            temp += pop.individus[i].instrument;
            label.Content = temp;
        }
     
      
    }
}
